/*
 * Copyright ShangHai ECLUB Information Technology Co.,Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at

 * http://www.apache.org/licenses/LICENSE-2.0

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.eclub.emotion.rootstone.server.core.communication.http;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.QueryStringDecoder;

/**
 * 
 * @author jun.yang, Wincor Nixdorf International GmbH
 */
public abstract class RequestUtils {

	private static final String ONLY_ACCEPT_CHARSET = "UTF-8";

	static com.eclub.emotion.rootstone.server.http.HttpRequest newHttpRequest(HttpRequest request) {
		com.eclub.emotion.rootstone.server.http.HttpRequest newHttpRequest = new com.eclub.emotion.rootstone.server.http.HttpRequest(request);

		Charset charset = determineCharset(request);
		Map<String, List<String>> queryParams = decodeQueryParams(request, charset);
		// headers
		Map<String, List<String>> valuesOfHeader = new HashMap<String, List<String>>();
		if (!request.getHeaderNames().isEmpty()) {
			for (String name : request.getHeaderNames()) {
				List<String> vList = new ArrayList<String>();
				for (String value : request.getHeaders(name)) {
					vList.add(value);
				}
				valuesOfHeader.put(name, vList);
			}
			newHttpRequest.setValuesOfHeader(valuesOfHeader);
		}

		newHttpRequest.setQueryParams(queryParams);
		newHttpRequest.setContent(request.getContent().array());
		return newHttpRequest;
	}

	private static Charset determineCharset(HttpRequest request) {
		return Charset.forName(ONLY_ACCEPT_CHARSET);
	}

	private static Map<String, List<String>> decodeQueryParams(HttpRequest request, Charset charset) {
		return new QueryStringDecoder(request.getUri(), charset).getParameters();
	}

}
